package java114.jdbc;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo02_DataSource {
    public static void main(String[] args) {

        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        DataSource dataSource = mysqlDataSource;
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
            //1     通过数据源对象获取数据库连接
            connection = dataSource.getConnection();
            //2  定义SQL语句
            String sql = "select id, name, sno, age, gender, enroll_date, class_id from student where name = ?";
            //预处理sql执行对象
            statement = connection.prepareStatement(sql);
            //接受用户输入
            System.out.println("请输入学生姓名：");
            Scanner scanner = new Scanner(System.in);
            String inName = scanner.next();

            //用真实值代替站位fu
            statement.setString(1,inName);
            //返回执行结果
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                Long id = resultSet.getLong("id");
                String name = resultSet.getString("name");
                String sno = resultSet.getString("sno");
                int age = resultSet.getInt("age");
                Long gender = resultSet.getLong("gender");
                Date enrollDate = resultSet.getDate("enroll_date");
                Long classId = resultSet.getLong("class_id");
                System.out.println(MessageFormat.format("id={0}, name={1}, sno={2}, age={3}, gender={4}, enroll_date={5}, class_id={6}",
                        id, name, sno, age, gender, enrollDate, classId));
            }


        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //7关闭连接
            if(resultSet != null){
                try{
                    resultSet.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }

            if(statement != null){
                try{
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection != null){
                try{
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
